<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Brand;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ProductTranslation;
use App\Models\ProductStock;
use App\Models\Category;
use App\Models\FlashDealProduct;
use App\Models\ProductTax;
use App\Models\AttributeValue;
use App\Models\Attribute;
use App\Models\Cart;

use App\Models\Role;
use App\Models\Staff;
use App\Models\FlashDeal;
use App\Models\User;
use App\Models\Color;
use App\Models\Seller;
use Auth;
use App\Models\Upload;
use Carbon\Carbon;
use Combinations;
use Artisan;
use Cache;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Str;
use App\Models\Shop;
use App\Models\BusinessSetting;

class ScrapeAndStoreProduct implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $item_id;
    protected $shop_id;
    protected $category_id;

    public function __construct($item_id, $shop_id, $category_id)
    {
        $this->item_id = $item_id;
        $this->shop_id = $shop_id;
        $this->category_id = $category_id;
    }

    public function handle()
    {
        // 在这里实现数据采集和存储的逻辑
        // 将 duplicate99 函数中的 foreach 循环体中的代码移动到这里，并根据需要进行适当的修改

        // 新增代码：从duplicate99函数中提取的采集和存储逻辑
        sleep(1);
        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => "https://api09.99api.com/",
            // You can set any number of default request options.
            'timeout' => 30,
        ]);

        $response = $client->get('/shopee/goodsDetail', [
            'query' => [
                'apikey' => '07B813F6C811BB8E81F75655FBB3AC75',
                'itemId' => $this->item_id,
                'shopId' => $this->shop_id,
                'market' => 'my',
            ],
        ]);
        $result = json_decode((string)$response->getBody(), true);
        Log::error("99detail info:" . json_encode($result));
        $remote_data = [];
        if ($result['retcode'] == '0000') {
            $remote_data = $result['data'];
            Log::error("采集到的产品信息是:" . json_encode($remote_data));
        } else {
            \Log::error("99 error:" . json_encode($result, JSON_UNESCAPED_UNICODE));
            return; // 使用 return 替换原本的 continue
        }

        $filter_sku = array_filter($remote_data['skus'], function ($v) {
            return !empty($v['name']) && ($v['price'] > 0);
        });
        if (count($filter_sku) == 0) {
            \Log::error("99 sku empty:" . json_encode($remote_data['name'], JSON_UNESCAPED_UNICODE));
            return; // 使用 return 替换原本的 continue
        }

        // 在这里，我们不需要 try-catch 和事务，因为 Job 类中的错误会自动重试
        // 第一遍处理基础数据
        // ...（这里省略了原本的代码，直接粘贴即可）
         // 第一遍处理基础数据
                $description = '';
                $product_name = '';
                $brand_name = '';
                $min_price = $max_price = 0;
                // 1.确定每个商品拥有的规格组(仅双规格可以加入)
                if (empty($remote_data['tierVariations'][0]['name']) || empty($remote_data['tierVariations'][1]['name'])) {
                    \Log::error("99 sku group empty:" . json_encode($remote_data['tierVariations'], JSON_UNESCAPED_UNICODE));
                    return;
                }
                $attribute1_model = Attribute::updateOrCreate([
                    'name' => $remote_data['tierVariations'][0]['name'],
                ], []);
                $attribute2_model = Attribute::updateOrCreate([
                    'name' => $remote_data['tierVariations'][1]['name'],
                ], []);
                $attr_arr = $temp_choice = [];
                $choice1_arr = ['attribute_id' => $attribute1_model->id, 'values' => []];
                $choice2_arr = ['attribute_id' => $attribute2_model->id, 'values' => []];
                // 处理属性产品类1和产品类2
                foreach ($remote_data['tierVariations'][0]['options'] as $vvv1) {
                    if (trim($vvv1)) {
                        $attribute_value_color_model = AttributeValue::updateOrCreate([
                            'attribute_id' => $attribute1_model->id, 'value' => $vvv1
                        ]);
                        $attr_arr[] = $attribute1_model->id;
                        $attr_arr = array_unique($attr_arr);
                        $choice1_arr['values'][] = $vvv1;
                        $choice1_arr['values'] = array_unique($choice1_arr['values']);
                    }
                }

                foreach ($remote_data['tierVariations'][1]['options'] as $vvv2) {
                    if (trim($vvv2)) {
                        $attribute_value_size_model = AttributeValue::updateOrCreate([
                            'attribute_id' => $attribute2_model->id, 'value' => $vvv2
                        ]);
                        $attr_arr[] = $attribute2_model->id;
                        $attr_arr = array_unique($attr_arr);
                        $choice2_arr['values'][] = $vvv2;
                        $choice2_arr['values'] = array_unique($choice2_arr['values']);
                    }
                }


                if (in_array($attribute1_model->id, $attr_arr)) {
                    $temp_choice[] = $choice1_arr;
                }
                if (in_array($attribute2_model->id, $attr_arr)) {
                    $temp_choice[] = $choice2_arr;
                }

                // 2.处理图片新增
                $image_ids = [];
                foreach ($remote_data['images'] as $image_url) {
                    $image_model = Upload::updateOrCreate([
                        'file_original_name' => $image_url
                    ], [
                        'file_name' => $image_url,
                        'user_id' => 0,
                        'file_size' => 8888,
                        'extension' => 'jpg',
                        'type' => 'image'
                    ]);
                    $image_ids[] = $image_model->id;
                }
                $description = $remote_data['description'];
                $product_name = $remote_data['name'];
                $brand_name = $remote_data['brand'];
                //$min_price = $remote_data['priceMin'];
                //$max_price = $remote_data['priceMax'];
                $pro_price = $remote_data['price']/100000;
                Log::error("pro_price的价格是:" . $pro_price);

                if (!$product_name || count($image_ids) == 0) {
                    return;
                }
                // 3.处理所属品牌
                if ($brand_name) {
                    $brand_model = Brand::updateOrCreate([
                        'name' => $brand_name,
                    ], [
                        'logo' => 0,
                        'top' => 0,
                        'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($brand_name))),
                        'meta_title' => $brand_name,
                        'meta_description' => $brand_name,
                    ]);
                }
                Log::error("要插入的产品分类ID:" . $category_id);
                // 主档案商品
                $product_model = Product::create([
                    'name' => $product_name,
                    'user_id' => 1,
                    'category_id' => 1,
                    'brand_id' => $brand_model ? $brand_model->id : 0,
                    'photos' => implode($image_ids, ','),
                    'thumbnail_img' => $image_ids ? $image_ids[0] : '',
                    'description' => $description,
                    'unit_price' => $pro_price/3,
                    'purchase_price' => 0,
                    'variant_product' => count($remote_data['skus']) > 1 ? 1 : 0,
                    'attributes' => json_encode($attr_arr),
                    'choice_options' => json_encode($temp_choice),
                    'colors' => json_encode([]),
                    'published' => 1,
                    'approved' => 1,
                    'current_stock' => count($remote_data['skus']) * 1000,
                    'min_qty' => 1,
                    'low_stock_quantity' => 1,
                    'discount' => 0,
                    'discount_type' => 'amount',
                    'shipping_type' => 'free',
                    'shipping_cost' => 0,
                    'meta_title' => $product_name,
                    'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($product_name))),
                    'refundable' => 0,
                    'cpk' => 1
                ]);
        
        // 第二轮处理子规格插入
        // ...（这里省略了原本的代码，直接粘贴即可）
        // 第二轮处理子规格插入
                $sku_num = 0;
                foreach ($remote_data['skus'] as $temp_sku) {
                    if($sku_num >=5){
                        break;
                    }
                    $sku_arr = [];
                    $child_spec1 = $remote_data['tierVariations'][0]['options'][$temp_sku['tier_index'][0]];
                    if (trim($child_spec1)) {
                        $sku_arr[] = str_replace(' ', '', $child_spec1);
                    }
                    $child_spec2 = $remote_data['tierVariations'][1]['options'][$temp_sku['tier_index'][1]];
                    if (trim($child_spec2)) {
                        $sku_arr[] = str_replace(' ', '', $child_spec2);
                    }
                    
                    $sku_price = $temp_sku['price']/100000;
                    Log::error("sku的价格是:" . $sku_price);
                    ProductStock::create([
                        'product_id' => $product_model->id,
                        'variant' => implode('-', $sku_arr),
                        'sku' => implode('-', $sku_arr),
                        'price' => $sku_price/3,
                        'qty' => 1000
                    ]);
                    $sku_num ++;
                }
                // 在这里结束新代码的添加
                }
    
}
